package cn.com.infohold.smartcity.activity.Chengbaofang;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import cn.com.infohold.smartcity.R;
import cn.com.infohold.smartcity.api.HttpEvent;
import cn.com.infohold.smartcity.api.SDK;
import cn.com.infohold.smartcity.api.bean.ChengBaoFangBean;
import cn.com.infohold.smartcity.api.bean.LandResult;
import cn.com.infohold.smartcity.api.bean.RelativeBean;
import cn.com.infohold.smartcity.bean.RelativeListBean;
import cn.com.infohold.smartcity.data.XmlData;
import cn.com.infohold.smartcity.parent.ParentActivity;
import cn.com.infohold.smartcity.utils.DialogUtils;
import cn.com.infohold.smartcity.utils.GsonUtil;
import cn.com.infohold.smartcity.utils.RecyclerViewDivider;
import cn.com.infohold.smartcity.utils.RequestCode;
import cn.com.infohold.smartcity.view.WheelView;
import common.annotation.ViewInject;
import common.dialog.ProgressDialog;
import library.utils.DisplayUtil;

/**
 * Created by Monsoon on 2017/11/8.
 */
public class ChengBaoFangAdd_Activity extends ParentActivity{

    @ViewInject(R.id.ib_back)
    ImageButton ib_back;
    @ViewInject(R.id.et_code)
    EditText et_code;
    @ViewInject(R.id.et_name)
    EditText et_name;
    @ViewInject(R.id.tv_contractortype)
    TextView tv_contractortype;
    @ViewInject(R.id.et_cardid)
    EditText et_cardid;
    @ViewInject(R.id.tv_sex)
    TextView tv_sex;
    @ViewInject(R.id.et_tel)
    EditText et_tel;
    @ViewInject(R.id.et_zipcode)
    EditText et_zipcode;
    @ViewInject(R.id.et_address)
    EditText et_address;
    @ViewInject(R.id.ll_relative)
    LinearLayout ll_relative;
    @ViewInject(R.id.ll_relativelist)
    LinearLayout ll_relativelist;
    @ViewInject(R.id.iv_arrow)
    ImageView iv_arrow;
    @ViewInject(R.id.ib_add)
    ImageButton ib_add;
    @ViewInject(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    @ViewInject(R.id.btn_commit)
    Button btn_commit;

    private ChengBaoFangBean chengBaoFangBean;
    private List<RelativeBean> relativeList = new ArrayList<>();
    boolean flag = true;
    private RLAdapter mAdapter;

    String[] typeStr = new String[]{"个人","农户","组织单位"};
    String[] sexStr = new String[]{"男","女"};


    @Override
    protected Object inflateView() {
        return R.layout.activity_add_chengbaofang;
    }

    @Override
    protected void initView(View anchor) {

        chengBaoFangBean = new ChengBaoFangBean();

        initRV();

        ib_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransitionFade();
            }
        });

        List<String> typeList = new ArrayList<>();
        Collections.addAll(typeList,typeStr);
        List<String> sexList = new ArrayList<>();
        Collections.addAll(sexList,sexStr);

        tv_contractortype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.createNewSelectedDialog(ChengBaoFangAdd_Activity.this, "承包方类型", new WheelView.OnWheelViewOkClickListener() {
                    @Override
                    public void onClick(View var1, int selectedIndex, String selectValue, List<Integer> selectIndexs, List<String> selectValues) {
                        if (tv_contractortype.getText().toString().equals(typeList.get(selectedIndex).toString())){
                            return;
                        }
                        String type = typeList.get(selectedIndex).toString();
                        tv_contractortype.setText(type);

                    }
                },typeList,tv_contractortype.getText().toString(),false,false,true);
            }
        });

        tv_sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.createNewSelectedDialog(ChengBaoFangAdd_Activity.this, "性别", new WheelView.OnWheelViewOkClickListener() {
                    @Override
                    public void onClick(View var1, int selectedIndex, String selectValue, List<Integer> selectIndexs, List<String> selectValues) {
                        if (tv_sex.getText().toString().equals(sexList.get(selectedIndex).toString())){
                            return;
                        }
                        String sex = sexList.get(selectedIndex).toString();
                        tv_sex.setText(sex);

                    }
                },sexList,tv_sex.getText().toString(),false,false,true);
            }
        });

        ll_relative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag == true){
                    flag = false;
                    ll_relativelist.setVisibility(View.GONE);
                    iv_arrow.setImageResource(R.drawable.arrows_up);
                }else {
                    flag = true;
                    ll_relativelist.setVisibility(View.VISIBLE);
                    iv_arrow.setImageResource(R.drawable.arrows_down);
                }
            }
        });

        ib_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(ChengBaoFangAdd_Activity.this, RelativeAdd_Activity.class), 100);
                overridePendingTransitionFade();
            }
        });

        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chengBaoFangBean.setCode(et_code.getText().toString());
                chengBaoFangBean.setName(et_name.getText().toString());
                switch (tv_contractortype.getText().toString()){
                    case "个人":
                        chengBaoFangBean.setContractortype(1);
                        break;
                    case "农户":
                        chengBaoFangBean.setContractortype(2);
                        break;
                    case "组织单位":
                        chengBaoFangBean.setContractortype(3);
                        break;
                    default:
                        break;
                }
                chengBaoFangBean.setCardid(et_cardid.getText().toString());
                chengBaoFangBean.setSex(tv_sex.getText().toString());
                chengBaoFangBean.setTel(et_tel.getText().toString());
                chengBaoFangBean.setZipcode(et_zipcode.getText().toString());
                chengBaoFangBean.setAddress(et_address.getText().toString());
                chengBaoFangBean.setStatus(1);
                chengBaoFangBean.setManager(XmlData.getInstance().getUserInfo().getId());
                
                initData(chengBaoFangBean);
            }
        });

    }

    private void initRV(){
        int dividerHeight = DisplayUtil.dp2px(0);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new RecyclerViewDivider(dividerHeight));
        mAdapter = new RLAdapter(relativeList);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initData(ChengBaoFangBean bean) {
        SDK.api().addChengbaofang(bean).postEvent(RequestCode.REQUEST_CODE_ADD_CHENGBAOFANG);
        ProgressDialog.show(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getData(HttpEvent<String> httpEvent) {

        int requestCode = httpEvent.getRequestCode();
        if (requestCode != RequestCode.REQUEST_CODE_ADD_CHENGBAOFANG
                && requestCode != RequestCode.REQUEST_CODE_ADD_RELATIVE) {
            ProgressDialog.dismiss();
            return;
        }

        if (httpEvent.getState() != HttpEvent.STATE_SUCCESS) {
            ProgressDialog.dismiss();
            return;
        } else {
            switch (requestCode) {
                case RequestCode.REQUEST_CODE_ADD_CHENGBAOFANG:
                    ProgressDialog.dismiss();
                    Type type = new TypeToken<LandResult<String>>() {
                    }.getType();
                    LandResult<String> result = GsonUtil.fromJson(httpEvent.getData(), type);
                    Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
                    if (result.getStatus().equals("1")) {
                        String contractorId = result.getResult();

                        RelativeListBean bean = new RelativeListBean();
                        String jsonStr = GsonUtil.toJson(relativeList);
                        bean.setRelatives(jsonStr);
                        bean.setContractorid(contractorId);
                        SDK.api().addRelative(bean).postEvent(RequestCode.REQUEST_CODE_ADD_RELATIVE);
                    }
                    break;
                case RequestCode.REQUEST_CODE_ADD_RELATIVE:
                    Type type1 = new TypeToken<LandResult<Map<String,String>>>(){}.getType();
                    LandResult<Map<String,String>> result1 = GsonUtil.fromJson(httpEvent.getData(),type1);

                    if (result1.getStatus().equals("1")){
                        finish();
                    }

                    break;

                default:
                    break;
            }
        }
    }

    class RLAdapter extends RecyclerView.Adapter<RLAdapter.mViewholder>{

        List<RelativeBean> mList;

        public RLAdapter(List<RelativeBean> mList) {
            this.mList = mList;
        }

        @Override
        public mViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
            mViewholder viewHolder = new mViewholder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_add_relative, parent, false));
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(mViewholder holder, int position) {
            RelativeBean bean = mList.get(position);

            holder.iv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    relativeList.remove(position);
                    mAdapter.notifyItemRemoved(position);
                    mAdapter.notifyItemRangeChanged(0, relativeList.size() - position);
                }
            });

            holder.tv_name.setText(bean.getName());
            switch (bean.getSex()){
                case 1:
                    holder.tv_sex.setText("男");
                    break;
                case 2:
                    holder.tv_sex.setText("女");
                    break;
                default:
                    break;
            }
            holder.tv_certificatecode.setText(bean.getCertificatecode());
            switch (bean.getEducation()){
                case 1:
                    holder.tv_education.setText("博士研究生");
                    break;
                case 2:
                    holder.tv_education.setText("硕士研究生");
                    break;
                case 3:
                    holder.tv_education.setText("大学本科");
                    break;
                case 4:
                    holder.tv_education.setText("大学专科");
                    break;
                case 5:
                    holder.tv_education.setText("中专/高中");
                    break;
                case 6:
                    holder.tv_education.setText("初中");
                    break;
                case 7:
                    holder.tv_education.setText("小学");
                    break;
                case 8:
                    holder.tv_education.setText("未知");
                    break;
                default:
                    break;
            }
            switch (bean.getRelationtype()){
                case 1:
                    holder.tv_relationtype.setText("配偶");
                    break;
                case 2:
                    holder.tv_relationtype.setText("父母");
                    break;
                case 3:
                    holder.tv_relationtype.setText("子女");
                    break;
                case 4:
                    holder.tv_relationtype.setText("兄弟姐妹");
                    break;
                default:
                    break;
            }
            holder.tv_specialty.setText(bean.getSpecialty());
            holder.tv_remark.setText(bean.getRemark());

        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        class mViewholder extends RecyclerView.ViewHolder{

            TextView tv_name;
            TextView tv_sex;
            TextView tv_certificatecode;
            TextView tv_education;
            TextView tv_relationtype;
            TextView tv_specialty;
            TextView tv_remark;
            ImageView iv_delete;

            public mViewholder(View itemView) {
                super(itemView);
                tv_name = (TextView) itemView.findViewById(R.id.tv_name);
                tv_sex = (TextView) itemView.findViewById(R.id.tv_sex);
                tv_certificatecode = (TextView) itemView.findViewById(R.id.tv_certificatecode);
                tv_education = (TextView) itemView.findViewById(R.id.tv_education);
                tv_relationtype = (TextView) itemView.findViewById(R.id.tv_relationtype);
                tv_specialty = (TextView) itemView.findViewById(R.id.tv_specialty);
                tv_remark = (TextView) itemView.findViewById(R.id.tv_remark);
                iv_delete = (ImageView) itemView.findViewById(R.id.iv_delete);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101){
            Bundle relative_bundle = data.getBundleExtra("relative_bundle");
            RelativeBean relativeResult = (RelativeBean) relative_bundle.getSerializable("relative");
            relativeList.add(relativeResult);
            mAdapter.notifyDataSetChanged();

        }
    }
}
